﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace JF.Controls
{
    public class EnumDropdown : ComboBox
    {
        public Type EnumType
        {
            get { return (Type)GetValue(EnumTypeProperty); }
            set { SetValue(EnumTypeProperty, value); }
        }

        public static readonly DependencyProperty EnumTypeProperty =
            DependencyProperty.Register("EnumType", typeof(Type), typeof(EnumDropdown), new PropertyMetadata(null, OnEnumTypeChanged));

        private static void OnEnumTypeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var dropdown = (EnumDropdown)d;
            if (dropdown.EnumType != null)
            {
                var enumValues = Enum.GetValues(dropdown.EnumType).Cast<Enum>();

                dropdown.ItemsSource = enumValues.Select(enumValue =>
                {
                    FieldInfo fieldInfo = enumValue.GetType().GetField(enumValue.ToString());
                    DescriptionAttribute[] attributes = (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
                    return new
                    {
                        Value = enumValue,
                        Description = attributes.Length > 0 ? attributes[0].Description : enumValue.ToString()
                    };
                }).ToList();

                dropdown.DisplayMemberPath = "Description";
                dropdown.SelectedValuePath = "Value";
            }
        }
    }
}
